<?php
define ("DOMAIN", "");
define ("PATH", "/");
//define ("COOKIEID", "encodeCookie");
define ("COOKIEID", "laohu_");
define ("COOKIEKEY", "raz"); 



class encodeCookie {
/**
* encodeCookie::$config
*
* configuration
*
*/
 	var $config;

/**
* encodeCookie::encodeCookie()
*
* constructor
*
*/
function encodeCookie () {
	$this->config = array ();
	$this->config['cookie_key'] = COOKIEKEY;
	$this->config['cookie'] = array (
				'cookie_id'				=>	COOKIEID,
				'cookie_path'			=>	PATH,
				'cookie_domain'			=>	DOMAIN,
	);
}

/**
* encodeCookie::set_Cookie()
*
* sets the cookie
*
* @param string $value
* @param integer $sticky
*/
function set_Cookie ($name, $value = "", $sticky = 0) {

    $exipres = "";

    if ($sticky == 1) {
        $expires = time() + 60*60*24*365;
    }

    $name = $this->config['cookie']['cookie_id'].$name;
    $newValue = $this->encodeC ($value);

    @setcookie($name, urlencode($newValue), $expires, $this->config['cookie']['cookie_path'], $this->config['cookie']['cookie_domain']);
}

/**
* encodeCookie::get_Cookie()
*
* gets the cookie
*
*/
function get_Cookie ($name) {

    if ( isset( $_COOKIE[$this->config['cookie']['cookie_id'].$name] ) ) {
    	$cookie = urldecode ( $_COOKIE[$this->config['cookie']['cookie_id'].$name] );
    	return $this->decodeC ($cookie);
    } else {
    	return FALSE;
    }

}

/**
* encodeCookie::encodeC()
*
* encodes the cookie
*
*/
function encodeC ($cookie) {

	$newcookie = array ();
    $cookie = base64_encode ($cookie);

    for ( $i=0; $i<=strlen ($cookie); $i++ ) {
    	$newcookie[ $i ] = ord ( $cookie[ $i ] ) * $this->encodeKey ();
    }

    $newcookie = implode ('.', $newcookie);

return $newcookie;
}

/**
* encodeCookie::decodeC()
*
* decodes the cookie
*
*/
function decodeC ($oldcookie) {

    $newcookie = array ();
	$cookie = explode ('.', $oldcookie);

    for ( $i=0; $i<=strlen ($oldcookie); $i++ ) {
    	$newcookie[ $i ] = chr ( $cookie[ $i ] / $this->encodeKey () );
    }

    $newcookie = implode ('', $newcookie);
    $newcookie = base64_decode ($newcookie);

return $newcookie;
}

/**
* encodeCookie::encodeKey()
*
* encodes the key
*
*/
function encodeKey () {
	$newkey = 0;
    for ( $i=0; $i<=strlen ( $this->config['cookie_key'] ); $i++ ) {
    	$newkey += ord ( $this->config['cookie_key'][ $i ] );
    }
return $newkey;
}

}


global $eC;
$eC = new encodeCookie;

function getUserIP() 
{ 
			if (@$_SERVER["HTTP_X_FORWARDED_FOR"]) 
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; 
			elseif (@$_SERVER["HTTP_CLIENT_IP"]) 
			$ip = $_SERVER["HTTP_CLIENT_IP"]; 
			elseif (@$_SERVER["REMOTE_ADDR"]) 
			$ip = $_SERVER["REMOTE_ADDR"]; 
			elseif (@getenv("HTTP_X_FORWARDED_FOR"))
			$ip = getenv("HTTP_X_FORWARDED_FOR"); 
			elseif (@getenv("HTTP_CLIENT_IP")) 
			$ip = getenv("HTTP_CLIENT_IP"); 
			elseif (@getenv("REMOTE_ADDR")) 
			$ip = getenv("REMOTE_ADDR"); 
			else 
			$ip = "Unknown"; 
			return $ip; 
}



//---设置COOKIE函数
function setcookieparam($param_name,$param_value)
{
		   global $the_session_name;
		   $the_session_name="laohu";
			setcookie($the_session_name."_".$param_name,$param_value,time()+3600,"/");
			$_COOKIE[$the_session_name."_".$param_name] = $param_value;

}

//---清理COOKIE函数
function clearcookieparam($param_name,$param_value)
{

	global $the_session_name;
	 $the_session_name="laohu";
	setcookie($the_session_name."_".$param_name,"",time()-1,"/");
	$_COOKIE[$the_session_name."_".$param_name] = "";
}



    
 
    
//--截取中文字符串函数
function cut_str($sourcestr,$cutlength) 
{ 
   $returnstr=''; 
   $i=0; 
   $n=0; 
   $str_length=strlen($sourcestr);//字符串的字节数 
   while (($n<$cutlength) and ($i<=$str_length)) 
   { 
      $temp_str=substr($sourcestr,$i,1); 
      $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码 
      if ($ascnum>=224)    //如果ASCII位高与224，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符         
         $i=$i+3;            //实际Byte计为3
         $n++;            //字串长度计1
      }
      elseif ($ascnum>=192) //如果ASCII位高与192，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符 
         $i=$i+2;            //实际Byte计为2
         $n++;            //字串长度计1
      }
      elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数仍计1个
         $n++;            //但考虑整体美观，大写字母计成一个高位字符
      }
      else                //其他情况下，包括小写字母和半角标点符号，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数计1个
         $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
      } 
   } 
         if ($str_length>$cutlength){
          $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
      }
    return $returnstr;

}

//截取utf-8字符串函数

function FSubstr($title,$start,$len="",$magic=true) 
{
/**
* powered by Smartpig
* 
*/

if($len == "") $len=strlen($title);

if($start != 0)
{
$startv = ord(substr($title,$start,1));
if($startv >= 128)
{
   if($startv < 192)
   {
    for($i=$start-1;$i>0;$i--)
    {
     $tempv = ord(substr($title,$i,1));
     if($tempv >= 192) break;
    }
    $start = $i;
   }
}
}

if(strlen($title)<=$len) return substr($title,$start,$len);

$alen   = 0;
$blen = 0;

$realnum = 0;

for($i=$start;$i<strlen($title);$i++)
{
$ctype = 0;
$cstep = 0;

$cur = substr($title,$i,1);
if($cur == "&")
{
   if(substr($title,$i,4) == "&lt;")
   {
    $cstep = 4;
    $length += 4;
    $i += 3;
    $realnum ++;
    if($magic)
    {
     $alen ++;
    }
   }
   else if(substr($title,$i,4) == "&gt;")
   {
    $cstep = 4;
    $length += 4;
    $i += 3;
    $realnum ++;
    if($magic)
    {
     $alen ++;
    }
   }
   else if(substr($title,$i,5) == "&amp;")
   {
    $cstep = 5;
    $length += 5;
    $i += 4;
    $realnum ++;
    if($magic)
    {
     $alen ++;
    }
   }
   else if(substr($title,$i,6) == "&quot;")
   {
    $cstep = 6;
    $length += 6;
    $i += 5;
    $realnum ++;
    if($magic)
    {
     $alen ++;
    }
   }
   else if(preg_match("/&#(\d+);?/i",substr($title,$i,8),$match))
   {
    $cstep = strlen($match[0]);
    $length += strlen($match[0]);
    $i += strlen($match[0])-1;
    $realnum ++;
    if($magic)
    {
     $blen ++;
     $ctype = 1;
    }
   }
}else{
   if(ord($cur)>=252)
   {
    $cstep = 6;
    $length += 6;
    $i += 5;
    $realnum ++;
    if($magic)
    {
     $blen ++;
     $ctype = 1;
    }
   }elseif(ord($cur)>=248){
    $cstep = 5;
    $length += 5;
    $i += 4;
    $realnum ++;
    if($magic)
    {
     $ctype = 1;
     $blen ++;
    }
   }elseif(ord($cur)>=240){
    $cstep = 4;
    $length += 4;
    $i += 3;
    $realnum ++;
    if($magic)
    {
     $blen ++;
     $ctype = 1;
    }
   }elseif(ord($cur)>=224){
    $cstep = 3;
    $length += 3;
    $i += 2;
    $realnum ++;
    if($magic)
    {
     $ctype = 1;
     $blen ++;
    }
   }elseif(ord($cur)>=192){
    $cstep = 2;
    $length += 2;
    $i += 1;
    $realnum ++;
    if($magic)
    {
     $blen ++;
     $ctype = 1;
    }
   }elseif(ord($cur)>=128){
    $length += 1;
   }else{
    $cstep = 1;
    $length +=1;
    $realnum ++;
    if($magic)
    {
     if(ord($cur) >= 65 && ord($cur) <= 90)
     {
      $blen++;
     }else{
      $alen++;
     }
    }
   }
}

if($magic)
{
   if(($blen*2+$alen) == ($len*2)) break;
   if(($blen*2+$alen) == ($len*2+1))
   {
    if($ctype == 1)
    {
     $length -= $cstep;
     break;
    }else{
     break;
    }
   }
}else{
   if($realnum == $len) break;
}
}

unset($cur);
unset($alen);
unset($blen);
unset($realnum);
unset($ctype);
unset($cstep);

return substr($title,$start,$length);
}


// -- 根据时间字符串切出所要求的字符来
function echo_timestamp_of_request($timestring)
{
    $timestring = substr($timestring,5,11);
    return $timestring;
}

// -- Cut num to return 1 per 100.
function cut_num($idd)
{
    $subd1 = $idd;
    if($subd1 <= 100)
    {
        $subd1 = "1";
    }
    else
    {
        $subd1 /= 100;
        is_string($subd1);
        $subd2 = substr(strchr($subd1,'.'),0);
        if($subd2 <>"")
        {
            $subd1 = str_replace($subd2,"", $subd1);
        }
        $subd1 +=1;
    }
    return $subd1;
}


  function getRandId()
    {
     	 
      $unique_id= md5(uniqid("")); 
      $a=substr($unique_id,0,3);
      return $a.(time());
   }

//取随机数函数--------
function getRandNumber ($fMin, $fMax) {
 srand((double)microtime()*1000000);

  $fLen = "%0".strlen($fMax)."d";

  Return sprintf($fLen, rand($fMin,$fMax));
 }


// -- Get a rand num.
function rand_num()
{
    srand((double)microtime()*100000000);
    $randval = rand();
    return $randval;
}

// -- Set Time out limit.
function set_time($times)
{
  @set_time_limit($times);
}

// -- 对有害信息进行过滤，并返回经过过滤的结果
function str_filter($strings_ch)
{
    $strings_ch = str_replace(">","&gt;",$strings_ch);
    $strings_ch = str_replace("<","&lt;",$strings_ch);
    $strings_ch = str_replace("_","",$strings_ch);
    $strings_ch = str_replace("%","",$strings_ch);
    $strings_ch = str_replace("\\'","’",$strings_ch);
    $strings_ch = str_replace("\\\"","”",$strings_ch);
    $strings_ch = htmlspecialchars($strings_ch);
    $strings_ch = str_replace("\n","<br>",$strings_ch);
    $strings_ch = str_replace("^","…",$strings_ch);
    return($strings_ch);
}

// -- 对有害信息进行过滤，并返回经过过滤的结果
function str_filter2($strings_ch)
{
    $strings_ch = str_replace(">","&gt;",$strings_ch);
    $strings_ch = str_replace("<","&lt;",$strings_ch);
    $strings_ch = str_replace("_","",$strings_ch);
    $strings_ch = str_replace("%","",$strings_ch);
    $strings_ch = str_replace("\\'","’",$strings_ch);
    $strings_ch = str_replace("\\\"","”",$strings_ch);
    $strings_ch = htmlspecialchars($strings_ch);
    $strings_ch = str_replace("^","…",$strings_ch);
    return($strings_ch);
}

// -- Login 过滤
function str_filter_login($strings_ch)
{
    $strings_ch = str_replace(">","&gt;",$strings_ch);
    $strings_ch = str_replace("<","&lt;",$strings_ch);
    //$strings_ch = str_replace("_","",$strings_ch);
    //$strings_ch = str_replace("%","",$strings_ch);
    //$strings_ch = str_replace("\\'","’",$strings_ch);
    //$strings_ch = str_replace("\\\"","”",$strings_ch);
    //$strings_ch = htmlspecialchars($strings_ch);
    //$strings_ch = str_replace("\n","<br>",$strings_ch);
    return($strings_ch);
}





//记录日志的函数
function log_write($type,$message)
{

$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if($type=="email")
 $the_log_file=$_SERVER['DOCUMENT_ROOT']."/log/log_email_".date("ymd").".log";
else
 $the_log_file=$_SERVER['DOCUMENT_ROOT']."/log/log_mobile_".date("ymd").".log";
echo "file:".$the_log_file;
//echo $the_log_file;
if ( !($fp = @fopen($the_log_file, "a+")))
{
//echo "error:\n\r";
echo("Warning: Cannot open log file \"".$the_log_file."\"\n");
  return FALSE;;
}
else
 echo "begin to log data\n\r";
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);


}


/**
 * 将字符串中的中文转换为unicode格式
 */
function chs2Unicode($str){
 return preg_replace_callback(
     "/[\x{4e00}-\x{9fa5}]+/u",
     create_function(
         '$matches',
         'return trim(json_encode($matches[0]),chr(34));'
     ),
     $str
 );
}

function cut_str2($string, $sublen, $start = 0, $code = 'UTF-8') 
{ 
    if($code == 'UTF-8') 
    { 
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/"; 
        preg_match_all($pa, $string, $t_string); 
 
        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."..."; 
        return join('', array_slice($t_string[0], $start, $sublen)); 
    } 
    else 
    { 
        $start = $start*2; 
        $sublen = $sublen*2; 
        $strlen = strlen($string); 
        $tmpstr = ''; 
 
        for($i=0; $i< $strlen; $i++) 
        { 
            if($i>=$start && $i< ($start+$sublen)) 
            { 
                if(ord(substr($string, $i, 1))>129) 
                { 
                    $tmpstr.= substr($string, $i, 2); 
                } 
                else 
                { 
                    $tmpstr.= substr($string, $i, 1); 
                } 
            } 
            if(ord(substr($string, $i, 1))>129) $i++; 
        } 
        if(strlen($tmpstr)< $strlen ) $tmpstr.= "..."; 
        return $tmpstr; 
    } 
} 

?>